from django.contrib import auth
from django.shortcuts import render

# Create your views here.
from django.contrib.auth import get_user_model
import random
import uuid
from django.http import HttpResponse, JsonResponse

from django.views.decorators.csrf import csrf_exempt

from dysms_python.demo_sms_send import send_sms
from users.models import UserProfile, VerifyCode
from django.http import HttpResponse
import json
import datetime
from datetime import timedelta
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from users.serializers import MobileUserSerializer
from rest_framework_jwt.views import JSONWebTokenAPIView
from django.forms.models import model_to_dict

User = get_user_model()



# def login(request):
#     if request.method == "POST":
#         mobile = request.POST.get('username', "")
#         verification_code = request.POST.get('register_code', "")
#         verify_records = VerifyCode.objects.filter(mobile=mobile).order_by("-add_time")
#         if verify_records:
#             last_record = verify_records[0]
#             one_mintes_ago = datetime.datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
#             if one_mintes_ago > last_record.add_time.replace(tzinfo=None):
#                 resp = {'respcode': 0, 'detail': '验证码已过期,请重新获取！'}
#                 return HttpResponse(json.dumps(resp), content_type="application/json")
#             if last_record.code != verification_code:
#                 resp = {'respcode': 0, 'detail': '验证码错误'}
#                 return HttpResponse(json.dumps(resp), content_type="application/json")
#             else:
#                 user = auth.authenticate(mobile=mobile)  # 用户验证
#                 if user:
#                     login(request, user)  # 用户登录
#                 resp = {'respcode': 1, 'detail': '登录成功！'}
#                 return HttpResponse(json.dumps(resp), content_type="application/json")

@csrf_exempt
def register(request):
    if request.method == "GET":
        company_name = request.GET.get("company_name")
        principal = request.GET.get("principal")
        mobile = request.GET.get("mobile")
        verification_code = request.GET.get('verification_code')
        verify_records = VerifyCode.objects.filter(mobile=mobile).order_by("-add_time")
        if verify_records:
            last_record = verify_records[0]
            one_mintes_ago = datetime.datetime.now() - timedelta(hours=0, minutes=1, seconds=0)
            if one_mintes_ago > last_record.add_time.replace(tzinfo=None):
                resp = {'respcode': 0, 'detail': '验证码已过期,请重新获取！'}
                return HttpResponse(json.dumps(resp), content_type="application/json")
            if last_record.code != verification_code:
                resp = {'respcode': 0, 'detail': '验证码错误'}
                return HttpResponse(json.dumps(resp), content_type="application/json")
            else:
                is_user_exist = UserProfile.objects.filter(username=mobile)
                if is_user_exist:
                    resp = {'respcode': 0, 'detail': '手机号已经注册'}
                    return HttpResponse(json.dumps(resp), content_type="application/json")
                else:
                    user = UserProfile.objects.create(company_name=company_name, username=mobile, principal=principal,
                                                      mobile=mobile)
                    user.save()
                    resp = {'respcode': 1, 'detail': '注册成功！'}
                    return HttpResponse(json.dumps(resp), content_type="application/json")

@csrf_exempt
def send_message(request):
    # """发送信息的视图函数"""
    # 获取ajax的get方法发送过来的手机号码
    phone_number = request.GET.get('mobile')
    sign_name = "广东原昇"
    template_code = "SMS_151996142"
    l = []
    for i in range(6):
        rand_num = random.randint(0, 9)
        l.append(str(rand_num))
    code = ''.join(l)
    print(code)
    __business_id = uuid.uuid1()
    result = send_sms(__business_id, phone_number, sign_name, template_code, '{"code":"' + code + '"}')
    verify_code = VerifyCode.objects.create(mobile=phone_number, code=code)
    verify_code.save()
    resp = {'respcode': 1, 'detail': code}
    return HttpResponse(json.dumps(resp), content_type="application/json")

@csrf_exempt
class CustomBackend(ModelBackend):
    """
    自定义用户验证
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = User.objects.get(Q(username=username) | Q(mobile=username))
            if user.check_password(password):
                return user
        except Exception as e:
            return None


class ObtainJSONWebToken(JSONWebTokenAPIView):
    """
    API View that receives a POST with a user's username and password.

    Returns a JSON Web Token that can be used for authenticated requests.
    """
    serializer_class = MobileUserSerializer

@csrf_exempt
def user_page(request):
    return render(request, 'html/main/user_information.html', None)
@csrf_exempt
def user_info(request):
    id = request.GET.get('id')
    user = UserProfile.objects.filter(id=id)
    return JsonResponse({"json_data":[model_to_dict(item) for item in user]})
@csrf_exempt
def is_exist_mobile(requst):
    mobile = requst.GET.get("mobile")
    is_user_exist = UserProfile.objects.filter(username=mobile)
    if is_user_exist:
        a = {'respcode': 1, 'detail': '验证码已发送，请注意查收'}

        return HttpResponse(json.dumps(a), content_type="application/json")
    else:
        b = {'respcode': 0, 'detail': '手机号未注册'}
        return HttpResponse(json.dumps(b), content_type="application/json")